import cv2
import numpy as np

img = cv2.imread('../imgs/handwriting.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))

img1 = img.copy()
cv2.drawContours(img1, contours, -1, (0,0,255), 2)
cv2.imshow('img1', img1)

img2 = img.copy()
cnt = contours[2]
cv2.drawContours(img2, [cnt], -1, (0,0,255), 2)
cv2.imshow('img2', img2)


area = cv2.contourArea(cnt)
print("area", area)
perimeter = cv2.arcLength(cnt, True)
print("perimeter", perimeter)
M = cv2.moments(cnt)
cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00']
print("cx", cx, "cy", cy)

cv2.waitKey()